home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 287 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: castle.nando.net!news
  2. From: actuary@nando.net   (Bill McCarthy)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: my atoi function, could someone suggest...
  5. Date: 4 Jan 1996 02:57:22 GMT
  6. Organization: News & Observer Public Access
  7. Message-ID: <4cffmi$rv2@castle.nando.net>
  8. References: <4cf7ap$q4u@kaleka.seanet.com>
  9. Reply-To: actuary@nando.net (Bill McCarthy)
  10. NNTP-Posting-Host: grail2007.nando.net
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4cf7ap$q4u@kaleka.seanet.com>, mitchell@seanet.com (where am i?) writes:
  14. >Hello.  This is my first attempt at an atoi function.  Although it
  15. >works and behaves just like atoi, I was wondering if anyone would care
  16. >for a look and make suggestions back to me about its efficiency.
  17. >
  18. >int atoi ( char *change )
  19. >{
  20. >    int newint = 0, sign = 1;
  21. >
  22. >    while ( *change )
  23. >    {
  24. >        if ( (*change < '0' || *change > '9') && *change != '-' )
  25. >        {
  26. >            *change++;
  27. >        }
  28. >        else
  29. >        {
  30. >            if ( *change == '-' )
  31. >            {
  32. >                *change++;
  33. >                if ( *change >= '0' && *change <= '9' )
  34. >                    sign = -1;
  35. >            }
  36. >            if ( *change >= '0' && *change <= '9' )
  37. >            {
  38. >                while ( sign )
  39. >                {
  40. >                    newint *= 10;
  41. >                    newint = newint + *change - 48;
  42. >                    *change++;
  43. >                    if ( *change < '0' || *change > '9' )
  44. >                    {
  45. >                        return (  newint * sign );
  46. >                        exit (0);
  47. >                    }
  48. >                }
  49. >            }
  50. >        }
  51. >    }
  52. >    return ( 0 );
  53. >}
  54.  
  55. I'm surprised your compiler didn't help you out.  You use exit() without
  56. including <stdlib.h>, the function can never get to exit(), you include
  57. the statement *change++ three times which is useless except for its
  58. side effect.
  59.  
  60. *change++ fetches and discards the char at change, then increments
  61. change.  That isn't particularly efficient, but may be optimized away.
  62.  
  63. More important is that your function does not duplicate the real atoi().
  64. Try "x89" as input.  The real atoi correctly returns 0.
  65.  
  66. Bill McCarthy
  67. actuary@nando.net
  68. Wendell, NC  USA
  69.  
  70.